var wxpay = require('../../../utils/pay.js');
var app = getApp();
var md5 = require("../../../utils/md5.js");
Page({
	data: {
    tabs: ["待付款", "待使用/配送", "待评价", "已完成"],
		tabClass: ["", "", "", ""],
    payArr: ["余额支付","微信支付"],
		stv: {
			windowWidth: 0,
			lineWidth: 0,
			offset: 1,
			tStart: true
		},
		activeTab: 1,
		loadingStatus: false,
	},
	onLoad: function (options) {
    let { tabs } = this.data;
    wx.setStorageSync('orderState', 1);
    var res = wx.getSystemInfoSync()
    this.windowWidth = res.windowWidth;
    this.data.stv.lineWidth = this.windowWidth / this.data.tabs.length;
    this.data.stv.windowWidth = res.windowWidth;
    this.setData({ stv: this.data.stv })
    this.tabsCount = tabs.length;
	},
	onShow: function () {
    var status = wx.getStorageSync('orderState');
    this._updateSelectedPage(status);
    this.getOrderList(status);
	},
	getOrderList: function (type) {
    var that = this;
    wx.setStorageSync('orderState', type);
    wx.showToast({
      title: '加载中',
      icon: 'loading'
    })
		// setTimeout(function(){
      var open_id = app.globalData.openId + '';
      var order_type = (type + 1) + '';
      var service = 'User.GetNewOrder';
      var shop_id = app.globalData.shopId;
      var user_id = app.globalData.userId;
      var sign = md5.md5(open_id + order_type + service + shop_id + user_id);
      wx.request({
        url: app.globalData.serviceUrl + 'User.GetNewOrder',
        header: {
          'Content-Type': 'json'
        },
        data: {
          sign: sign,
          user_id: user_id,
          open_id: open_id,
          order_type: order_type,
          shop_id: shop_id
        },
        success: function(res)  {
          wx.hideToast()
          var result = res.data.data;
          if (result.code == 0) {
            var orderList = [];
            for (let i = 0; i < result.info.length; i++) {
              var line = result.info[i];
              var delive_type = result.info[i].delive_type;
              var order_pid = result.info[i].order_pid;
              var order_hexiao = result.info[i].order_hexiao;
              var pinglun = result.info[i].pinglun;
              var status = result.info[i].status;
              var statusType = '';
              if (delive_type == 1) {
                if (order_pid == 1) {
                  statusType = '待支付';
                }
                if (order_pid == 2 && order_hexiao == 1 && pinglun == 0) {
                  statusType = '待使用';
                }
                if (order_pid == 2 && order_hexiao == 2 && pinglun == 0) {
                  statusType = '待评价';
                }
                if (order_pid == 2 && pinglun == 1) {
                  statusType = '交易完成';
                }

                if (status == 5 && order_pid == 3) {
                  statusType = '已退款';
                }
              }
              if (delive_type == 2) {
                if (status == 0) {
                  statusType = '待支付';
                }
                if (status == 1) {
                  statusType = '待接单';
                }
                if (status == 2) {
                  statusType = '待配送';
                }
                if (status == 3) {
                  statusType = '配送中';
                }
                if (status == 4 && pinglun != 1) {
                  statusType = '待评价';
                }
                if (status == 4 && pinglun == 1) {
                  statusType = '交易完成';
                }

                if (status == 5 && order_pid == 3) {
                  statusType = '已退款';
                }
              }

              line.status = type;
              line.statusStr = statusType;
              orderList.push(line);
            }
            that.setData({
              orderList: orderList
            });
          } else {
            that.setData({
              orderList: 'null',
            });
            return;
          }
        },
        complete: function (res) {
          wx.hideToast()
          console.log(res);
        },
      })
    // },2000)
	},
	orderDetail: function (e) {
		var orderId = e.currentTarget.dataset.id;
		var ordernum = e.currentTarget.dataset.ordernum;
		var tyep = e.currentTarget.dataset.type;
    var shop_id = e.currentTarget.dataset.shopid;
		if (tyep == 3){
		  wx.navigateTo({
        url: "/pages/order-comment/index?id=" + orderId + "&shop_id=" + shop_id
		  })
		}else{
			wx.navigateTo({
				url: "/pages/order-details/index?id=" + orderId + "&ordernum="+ordernum
			})
		}	
	},
  handlerStart(e) {
    console.log('handlerStart')
    let { clientX, clientY } = e.touches[0];
    this.startX = clientX;
    this.tapStartX = clientX;
    this.tapStartY = clientY;
    this.data.stv.tStart = true;
    this.tapStartTime = e.timeStamp;
    this.setData({ stv: this.data.stv })
  },
  handlerMove(e) {
    console.log('handlerMove')
    let { clientX, clientY } = e.touches[0];
    let { stv } = this.data;
    let offsetX = this.startX - clientX;
    this.startX = clientX;
    stv.offset += offsetX;
    if (stv.offset <= 0) {
      stv.offset = 0;
    } else if (stv.offset >= stv.windowWidth * (this.tabsCount - 1)) {
      stv.offset = stv.windowWidth * (this.tabsCount - 1);
    }
    this.setData({ stv: stv });
  },
  handlerCancel(e) {

  },
  handlerEnd(e) {
    console.log('handlerEnd')
    let { clientX, clientY } = e.changedTouches[0];
    let endTime = e.timeStamp;
    let { tabs, stv, activeTab } = this.data;
    let { offset, windowWidth } = stv;
    //快速滑动
    if (endTime - this.tapStartTime <= 300) {
      console.log('快速滑动')
      //判断是否左右滑动(竖直方向滑动小于50)
      if (Math.abs(this.tapStartY - clientY) < 50) {
        //Y距离小于50 所以用户是左右滑动
        console.log('竖直滑动距离小于50')
        if (this.tapStartX - clientX > 5) {
          //向左滑动超过5个单位，activeTab增加
          console.log('向左滑动')
          if (activeTab < this.tabsCount - 1) {
            this.setData({ activeTab: ++activeTab })
          }
        } else if (clientX - this.tapStartX > 5) {
          //向右滑动超过5个单位，activeTab减少
          console.log('向右滑动')
          if (activeTab > 0) {
            this.setData({ activeTab: --activeTab })
          }
        }
        stv.offset = stv.windowWidth * activeTab;
      } else {
        //Y距离大于50 所以用户是上下滑动
        console.log('竖直滑动距离大于50')
        let page = Math.round(offset / windowWidth);
        if (activeTab != page) {
          this.setData({ activeTab: page })
        }
        stv.offset = stv.windowWidth * page;
      }
    } else {
      let page = Math.round(offset / windowWidth);
      if (activeTab != page) {
        this.setData({ activeTab: page })
      }
      stv.offset = stv.windowWidth * page;
    }
    stv.tStart = false;
    this.setData({ stv: this.data.stv })
  },
  	////////
  	_updateSelectedPage(page) {
	  	console.log('_updateSelectedPage')
	  	let { tabs, stv, activeTab } = this.data;
	  	activeTab = page;
	  	this.setData({ activeTab: activeTab })
	  	stv.offset = stv.windowWidth * activeTab;
	  	this.setData({ stv: this.data.stv })
  	},
  	handlerTabTap(e) {
  		this._updateSelectedPage(e.currentTarget.dataset.index);
      this.getOrderList(e.currentTarget.dataset.index);
  	},
  //事件处理函数
  swiperchange: function (e) {
    console.log('swiperCurrent',e.detail.current)
    let { tabs, stv, activeTab } = this.data;
    activeTab = e.detail.current;
    this.setData({ activeTab: activeTab })
    stv.offset = stv.windowWidth * activeTab;
    this.setData({ stv: this.data.stv })
  },
  toIndexPage: function () {
    wx.switchTab({
      url: "/pages/classification/index"
    });
  },
  showQr:function(e){
    var order_num = e.currentTarget.dataset.num
    wx.navigateTo({
      url: '/pages/order/hexiao?order_num='+order_num, //
    })
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    if (e.detail.value == 0) {
      this.toPayCredit(e);
    } else {
      this.toPayTap(e);
    }
  },
  toPayTap: function (e) {
    wx.showToast({
      title: '微信支付中',
      icon: 'loading'
    })
    var that = this;
    var client = 'wxa';
    var cost = e.currentTarget.dataset.money;
    var openid = app.globalData.openId;
    var order_id = e.currentTarget.dataset.id;
    var order_num = e.currentTarget.dataset.number;
    var service = 'Pay.Index';
    var type = 'wechat';
    var user_id = app.globalData.userId;
    var sign = md5.md5(client + cost + openid + order_id + order_num + service + type + user_id);
    wx.request({
      url: app.globalData.serviceUrl + 'Pay.Index',
      header: {
        'Content-Type': 'json'
      },
      data: {
        client: client,
        cost: cost,
        openid: openid,
        order_id: order_id,
        order_num: order_num,
        type: type,
        user_id: user_id,
        sign: sign,
      },
      success: function (res) {
        wx.hideToast()
        var result = res.data.data;
        if (result.code != 0) {
          wx.showModal({
            title: '失败',
            content: result.msg,
            showCancel: false
          })
          return;
        }
        wxpay.wxpay(app, cost, order_num, "/pages/ucenter/order-list/index", 'product', order_id, md5);
      },
      complete: function (res) {
        wx.hideToast()
        console.log(res);
      },
    })
  },
  toPayCredit: function (e) {
    wx.showToast({
      title: '余额支付中',
      icon: 'loading'
    })
    var that = this;
    var client = 'wxa';
    var cost = e.currentTarget.dataset.money;
    var openid = app.globalData.openId;
    var order_id = e.currentTarget.dataset.id;
    var order_num = e.currentTarget.dataset.number;
    var service = 'Pay.Index';
    var type = 'credit';
    var user_id = app.globalData.userId;
    var sign = md5.md5(client + cost + openid + order_id + order_num + service + type + user_id);
    wx.request({
      url: app.globalData.serviceUrl + 'Pay.Index',
      header: {
        'Content-Type': 'json'
      },
      data: {
        client: client,
        cost: cost,
        openid: openid,
        order_id: order_id,
        order_num: order_num,
        type: type,
        user_id: user_id,
        sign: sign,
      },
      success: function (res) {
        wx.hideToast();
        var result = res.data.data;
        if (result.code != 0) {
          wx.showModal({
            title: '支付失败',
            content: result.msg,
            showCancel: false
          })
        } else {
          wx.showModal({
            title: '支付成功',
            content: result.msg,
            showCancel: false
          })
          var status = wx.getStorageSync('orderState');
          that.getOrderList(status)
        }
      },
      complete: function (res) {
        wx.hideToast();
        console.log(res);
      },
    })
  },
  onUnload:function(){
    var that = this
    if(getCurrentPages().length>2){
      var pages = getCurrentPages()
      var curPage = pages[pages.length-2]
      var data = curPage.data
      curPage.setData({'isback':true})
    }
  }
})